package com.xbongbong.paas.script.distributor.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.help.menu.InitDistributorMenuHelp;
import com.xbongbong.paas.help.menu.InitMenuHelp;
import com.xbongbong.paas.help.menu.InitOrderCenterMenuHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.pojo.dto.ProcessOpenDistributorDTO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.PaasProcessTemplateService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.DistributorMenuEnum;
import com.xbongbong.pro.enums.menu.enums.OrderCenterMenuEnum;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.pro.script.pojo.dto.ProductDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OrderOutStockEnum;
import com.xbongbong.saas.enums.business.ReturnEnum;
import com.xbongbong.saas.help.BatchSeqExplainHelp;
import com.xbongbong.saas.script.help.InitExplainsHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * @author lee
 * @version v1.0
 * @date 2020/12/21 08:55
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/distributor")
public class DistributorExplainScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(DistributorExplainScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private InitDistributorMenuHelp initDistributorMenuHelp;
    @Resource
    private PaasProcessTemplateService paasProcessTemplateService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private InitMenuHelp initMenuHelp;
    @Resource
    private InitOrderCenterMenuHelp initOrderCenterMenuHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    @RequestMapping(value = "/addDistributorExplain", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String addStockMenu(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        String corpid = productDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("columns", "corpid");
        param.put("corpid", corpid);
        List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
        if (companyEntityList.isEmpty()) {
            return "corpid not exist";
        }
        // 加一下公司的套餐信息

        MenuInitDTO menuInitDTO = new MenuInitDTO();
        BeanUtil.copyProperties(productDTO, menuInitDTO, true);
        menuInitDTO.setAlias(XbbRefTypeEnum.DISTRIBUTOR.getAlias());
        initMenuHelp.menuInit(menuInitDTO);
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        return "success";
    }

    @RequestMapping(value = "/repairExplain", method = RequestMethod.POST)
    public String initExplain(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        String corpid = productDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("corpid", corpid);
        param.put("businessTypeIn", Arrays.asList(DistributorMenuEnum.DISTRIBUTOR.getCode(), DistributorMenuEnum.DISTRIBUTOR_ACCOUNT.getCode(), DistributorMenuEnum.DISTRIBUTOR_COMMUNICATE.getCode(), DistributorMenuEnum.CONTACT.getCode()));
        param.put("distributorMark", DistributorMarkEnum.DISTRIBUTOR.getCode());
        List<PaasFormExplainEntity> paasFormExplainEntities = paasFormExplainModel.findEntitys(param);
        Map<Integer, List<FieldAttrEntity>> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (DistributorMenuEnum distributorMenuEnum : DistributorMenuEnum.values()) {
            List<FieldAttrEntity> fieldList = InitExplainsHelper.initFieldAttrEntity(distributorMenuEnum.getAlias(), null, null, 1);
            explainMap.put(distributorMenuEnum.getCode(), fieldList);
        }
        paasFormExplainEntities.forEach(item -> item.setExplains(JSON.toJSONString(explainMap.get(item.getBusinessType()))));
        paasFormExplainModel.updateBatch(paasFormExplainEntities, corpid);
        JSONObject object = new JSONObject();
        object.put("success", "成功");
        return object.toJSONString();
    }

    @RequestMapping(value = "/addMarketingExplain", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String addMarketingExplain(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        String corpid = productDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("columns", "corpid");
        param.put("corpid", corpid);
        List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
        if (companyEntityList.isEmpty()) {
            return "corpid not exist";
        }
        MenuInitDTO menuInitDTO = new MenuInitDTO();
        BeanUtil.copyProperties(productDTO, menuInitDTO, true);
        menuInitDTO.setAlias(XbbRefTypeEnum.MARKETING_MANAGEMENT.getAlias());
        initMenuHelp.menuInit(menuInitDTO);
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        return "success";
    }


    @RequestMapping(value = "/addOrderCenterExplain", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String addOrderMenu(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        List<String> corpidList = productDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)){
            corpidList = companyModel.getCorpidList();
        }
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("del", 0);
            param.put("columns", "corpid");
            param.put("corpid", corpid);
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            if (companyEntityList.isEmpty()) {
                return "corpid not exist";
            }
            MenuInitDTO menuInitDTO = new MenuInitDTO();
            BeanUtil.copyProperties(productDTO, menuInitDTO, true);
            menuInitDTO.setAlias(XbbRefTypeEnum.ORDER_CENTER.getAlias());
            initMenuHelp.menuInit(menuInitDTO);
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        return "success";
    }

    @RequestMapping(value = "/repairOrderCenterExplain", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String initOrderExplain(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        List<String> corpidList = productDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)){
            corpidList = companyModel.getCorpidList();
        }
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("del", 0);
            param.put("corpid", corpid);
            param.put("businessTypeIn", Arrays.asList(OrderCenterMenuEnum.ORDER.getCode(),OrderCenterMenuEnum.RETURN.getCode()));
            param.put("distributorMark", DistributorMarkEnum.DISTRIBUTOR.getCode());
            List<PaasFormExplainEntity> paasFormExplainEntities = paasFormExplainModel.findEntitys(param);
            if (paasFormExplainEntities.size() == BasicConstant.ZERO){
                continue;
            }
            PaasFormEntityExt paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),corpid);
            if (Objects.isNull(paasFormEntity)) {
                paasFormEntity = paasFormModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(),corpid);
            }
            // 批次序列号解释需要都配置
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getAlias(), corpid);
            boolean isUseBatch = Objects.nonNull(companyConfigEntity) && Objects.equals(companyConfigEntity.getConfigValue(), BasicConstant.IS_USE.toString());
            Map<Integer, List<FieldAttrEntity>> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (OrderCenterMenuEnum orderCenterMenuEnum : OrderCenterMenuEnum.values()) {
                List<FieldAttrEntity> fieldList = InitExplainsHelper.initFieldAttrEntity(orderCenterMenuEnum.getAlias(), paasFormEntity, null, 1);
                if (Objects.equals(orderCenterMenuEnum.getCode(), XbbRefTypeEnum.REFUND.getCode())) {
                    out:
                    for (FieldAttrEntity attrEntity : fieldList) {
                        if (Objects.equals(attrEntity.getAttr(), ReturnEnum.PRODUCTS.getAttr())) {
                            for (FieldAttrEntity subAttrEntity : attrEntity.getSubForm().getItems()) {
                                if (Objects.equals(subAttrEntity.getAttr(), SelectProductEnum.SOURCE_DOC.getAttr())) {
                                    subAttrEntity.setAttrName("源出库发货单");
                                    break out;
                                }
                            }
                        }
                    }
                    if (isUseBatch) {
                        String productAttr = ReturnEnum.PRODUCTS.getAttr();
                        BatchSeqExplainHelp.getInstance().formatExplain4BatchAffectProductAttr(fieldList, BasicConstant.IS_USE.toString(), productAttr);
                    }
                }
                explainMap.put(orderCenterMenuEnum.getCode(), fieldList);
            }
            paasFormExplainEntities.forEach(item -> item.setExplains(JSON.toJSONString(explainMap.get(item.getBusinessType()))));
            paasFormExplainModel.updateBatch(paasFormExplainEntities, corpid);
        }
        JSONObject object = new JSONObject();
        object.put("success", "成功");
        return object.toJSONString();
    }

    @RequestMapping(value = "/addOrderOutStockFormExplain", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String addOrderOutStockForm(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        List<String> corpidList = productDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)){
            corpidList = companyModel.getCorpidList();
        }
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("del", 0);
            param.put("columns", "corpid");
            param.put("corpid", corpid);
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            if (companyEntityList.isEmpty()) {
                return "corpid not exist";
            }
            MenuInitDTO menuInitDTO = new MenuInitDTO();
            BeanUtil.copyProperties(productDTO, menuInitDTO, true);
            menuInitDTO.setAlias(XbbRefTypeEnum.ORDER_CENTER.getAlias());
            initOrderCenterMenuHelp.initOrderOutStock(menuInitDTO);
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        return "success";
    }

    @RequestMapping(value = "/repairOrderOutStockExplain", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String repairOrderOutStockExplain(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        List<String> corpidList = productDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)){
            corpidList = companyModel.getCorpidList();
        }
        for (String corpid : corpidList) {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType4Distributor(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode());
            if (Objects.isNull(paasFormExplainEntity)){
                continue;
            }
            PaasFormEntityExt paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),corpid);
            if (Objects.isNull(paasFormEntity)) {
                paasFormEntity = paasFormModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(),corpid);
            }
            List<FieldAttrEntity> fieldList = InitExplainsHelper.initFieldAttrEntity(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getAlias(), paasFormEntity, null, DistributorMarkEnum.DISTRIBUTOR.getCode());
            // 批次序列号解释需要都配置
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getAlias(), corpid);
            boolean isUseBatch = Objects.nonNull(companyConfigEntity) && Objects.equals(companyConfigEntity.getConfigValue(), BasicConstant.IS_USE.toString());
            if (isUseBatch) {
                String productAttr = OrderOutStockEnum.PRODUCT.getAttr();
                BatchSeqExplainHelp.getInstance().formatExplain4BatchAffectProductAttr(fieldList, BasicConstant.IS_USE.toString(), productAttr);
            }
            paasFormExplainEntity.setExplains(JSON.toJSONString(fieldList));
            paasFormExplainModel.update(paasFormExplainEntity);
        }
        JSONObject object = new JSONObject();
        object.put("success", "成功");
        return object.toJSONString();
    }

    /**
     * 开启/关闭经销商时，初始化/关闭(隐藏)/开启(显示)对应的菜单、form、explain
     * curl  http://127.0.0.1:2019/pro/v1/script/distributor/initFund -X POST -H 'Content-type: application/json' -d '{"frontDev":"1","xbbCode":123456,"corpid": "1","userId" : "1","platform":"web", "enable": 1}'
     * （1）菜单：在线支付流水菜单
     * （2）form：初始化/关闭(隐藏)/开启(显示)，没有的时候初始化，初始化后只能更新-即关闭或开启。包含业务有：在线支付流水、回款计划、销项发票、应收款、回款单、预收款余额
     * （3）explain：只存在初始化，不用更新（通过form控制显隐）
     * @param productDTO
     * @param br
     * @return java.lang.String
     * @throws Exception
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    @RequestMapping(value = "/initFund", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String initFund(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        EnableEnum enableEnum = EnableEnum.getByCode(productDTO.getEnable());
        if (Objects.isNull(enableEnum) || Objects.equals(enableEnum, EnableEnum.UNKNOWN)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        String corpid = productDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("columns", "corpid");
        param.put("corpid", corpid);
        List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
        if (companyEntityList.isEmpty()) {
            return "corpid not exist";
        }
        MenuInitDTO menuInitDTO = new MenuInitDTO();
        BeanUtil.copyProperties(productDTO, menuInitDTO, true);
        menuInitDTO.setAlias(XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getAlias());
        initDistributorMenuHelp.initFund(enableEnum, menuInitDTO);
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        return "success";
    }

    /**
     * 初始化信用管理菜单脚本测试
     * curl  http://127.0.0.1:2019/pro/v1/script/distributor/initCreditMenu -X POST -H 'Content-type: application/json' -d '{"frontDev":"1","xbbCode":123456,"corpid":"xbbxingdemo","userId":"xing001","platform":"web","saasMark":1,"distributorMark":1}'
     * @param menuInitDTO - 需要 corpid, userid, distributorMark
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initCreditMenu", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String initCreditMenu(@RequestBody @Valid MenuInitDTO menuInitDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(menuInitDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        String corpid = menuInitDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("columns", "corpid");
        param.put("corpid", corpid);
        List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
        if (companyEntityList.isEmpty()) {
            return "corpid not exist";
        }
        initDistributorMenuHelp.initCreditMenu(menuInitDTO);
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        return "success";
    }

    /**
     * 信用额度默认审批流初始化测试 - 自测，不必在测试环境执行
     * http://localhost:2019/pro/v1/script/distributor/initCreditProcess
     * 5520: {"corpid":"xbbxingdemo","userId":"xing001","platform":"web","frontDev":"1","xbbCode":123456,"appId":4523,"menuId":23843,"formId":19037,"businessType":5520,"distributorMark":1}
     * 5530:
     * @author xingxing.xiao
     */
    @RequestMapping(value = "/initCreditProcess", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String initCreditProcess(@RequestBody @Valid ProcessOpenDistributorDTO processOpenDistributorDTO, BindingResult br) throws Exception {
        LocaleContextHolder.setLocale(Locale.CHINA);
        paasProcessTemplateService.createProcess4Distributor(processOpenDistributorDTO);
        return "success";
    }
    /**
     * 将合同产品的发货数量解释attr从num_10修改为num_51
     * @param fixDataJobDTO
     * @param br
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/8/5 9:30
     * @version 1.0
     */
    @RequestMapping(value = "/repairShipmentsNumExplain", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void repairShipmentsNumExplain(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.COLUMNS, ParameterConstant.CORPID);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("status", BasicConstant.ONE);
            param.put("feeEndTimeGte", DateTimeUtil.getInt());
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            companyEntityList.forEach(i -> corpidList.add(i.getCorpid()));
            // 刷默认模板
            corpidList.add("0");
        }
        LOG.warn("数据库中共有公司{}家", corpidList.size());

        for (int i = 0; i < corpidList.size(); i++) {
            String corpid = corpidList.get(i);
            // 获取订货单解释
            int businessType = XbbRefTypeEnum.CONTRACT.getCode();
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(StringConstant.BUSINESS_TYPE, businessType);
            param.put(StringConstant.DISTRIBUTOR_MARK, DistributorMarkEnum.DISTRIBUTOR.getCode());
            List<PaasFormExplainEntity> formExplainEntityList = paasFormExplainModel.findEntitys(param);
            // 没解释直接跳过
            if (CollectionsUtil.isEmpty(formExplainEntityList)) {
                LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
                continue;
            }
            // 将解释中的num_10替换为num_51
            boolean needUpdate = false;
            for (PaasFormExplainEntity paasFormExplainEntity : formExplainEntityList) {
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
                if (explainMap.containsKey(OrderEnum.PRODUCT.getAttr())) {
                    FieldAttrEntity selectProduct = explainMap.get(OrderEnum.PRODUCT.getAttr());
                    SubFormPoJo subForm = selectProduct.getSubForm();
                    if (Objects.nonNull(subForm)) {
                        for (FieldAttrEntity item : subForm.getItems()) {
                            if (Objects.equals(item.getAttr(), "num_10")) {
                                needUpdate = true;
                                item.setAttr("num_51");
                                break;
                            }
                        }
                    }
                }
                paasFormExplainEntity.setExplains(JSON.toJSONString(explainMap.values()));
            }
            // 更新
            if (needUpdate) {
                paasFormExplainModel.updateBatch(formExplainEntityList, corpid);
            }
            LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
        }
        // 清除默认模板缓存
        String key = "0" + "_" + XbbRefTypeEnum.CONTRACT.getCode() + "_" + DistributorMarkEnum.DISTRIBUTOR.getCode();
        paasRedisHelper.removeValue(RedisPrefixConstant.FIELD_EXPLANATION, key);

        LOG.warn("consume:{}s", (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
    }

    /**
     * 将合同产品的促销解释attr从text_19修改为text_21
     * @param fixDataJobDTO
     * @param br
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/8/5 9:30
     * @version 1.0
     */
    @RequestMapping(value = "/repairPromotionExplain", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void repairPromotionExplain(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        LocaleContextHolder.setLocale(Locale.CHINA);
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.COLUMNS, ParameterConstant.CORPID);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("status", BasicConstant.ONE);
            param.put("feeEndTimeGte", DateTimeUtil.getInt());
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            companyEntityList.forEach(i -> corpidList.add(i.getCorpid()));
            // 刷默认模板
            corpidList.add("0");
        }
        LOG.warn("数据库中共有公司{}家", corpidList.size());

        for (int i = 0; i < corpidList.size(); i++) {
            String corpid = corpidList.get(i);
            // 获取订货单解释
            int businessType = XbbRefTypeEnum.CONTRACT.getCode();
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(StringConstant.BUSINESS_TYPE, businessType);
            param.put(StringConstant.DISTRIBUTOR_MARK, DistributorMarkEnum.DISTRIBUTOR.getCode());
            List<PaasFormExplainEntity> formExplainEntityList = paasFormExplainModel.findEntitys(param);
            // 没解释直接跳过
            if (CollectionsUtil.isEmpty(formExplainEntityList)) {
                LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
                continue;
            }
            // 将解释中的text_19修改为text_21
            boolean needUpdate = false;
            for (PaasFormExplainEntity paasFormExplainEntity : formExplainEntityList) {
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
                if (explainMap.containsKey(OrderEnum.PRODUCT.getAttr())) {
                    FieldAttrEntity selectProduct = explainMap.get(OrderEnum.PRODUCT.getAttr());
                    SubFormPoJo subForm = selectProduct.getSubForm();
                    if (Objects.nonNull(subForm)) {
                        for (FieldAttrEntity item : subForm.getItems()) {
                            if (Objects.equals(item.getAttr(), "text_19")) {
                                needUpdate = true;
                                item.setAttr("text_21");
                                break;
                            }
                        }
                    }
                }
                paasFormExplainEntity.setExplains(JSON.toJSONString(explainMap.values()));
            }
            // 更新
            if (needUpdate) {
                paasFormExplainModel.updateBatch(formExplainEntityList, corpid);
            }
            LOG.warn("公司{}:{}/{}", corpid, i + 1, corpidList.size());
        }
        // 清除默认模板缓存
        String key = "0" + "_" + XbbRefTypeEnum.CONTRACT.getCode() + "_" + DistributorMarkEnum.DISTRIBUTOR.getCode();
        paasRedisHelper.removeValue(RedisPrefixConstant.FIELD_EXPLANATION, key);

        LOG.warn("consume:{}s", (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
    }
}
